package com.hichat.provider.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hichat.common.pojo.Friend;
import com.hichat.common.pojo.FriendExample;
import com.hichat.common.util.QueryData;
import com.hichat.common.util.ReturnResult;
import com.hichat.provider.mapper.FriendMapper;

@Service
public class FriendServiceImpl {

    @Autowired
    private FriendMapper friendMapper;

    @Transactional
    public ReturnResult insertFriend(Friend friend) {
        if (null == friend || null == friend.getFromUserId() || null == friend.getToUserId()) {
            return ReturnResult.build(400,"添加好友失败");
        }
        List<Friend> list = friendMapper.getFriendByFromAndTo(friend.getFromUserId(), friend.getToUserId());
        if (list != null && !list.isEmpty()) {
            return ReturnResult.build(400,"好友已存在");
        }
        int insert = friendMapper.insert(friend);
        Friend friendOther = new Friend();
        friendOther.setFromUserId(friend.getToUserId());
        friendOther.setToUserId(friend.getFromUserId());
        int insert1 = friendMapper.insert(friendOther);
        if(insert > 0 && insert1 > 0){
            return ReturnResult.ok();
        }
        return ReturnResult.build(400,"添加好友失败");
    }

    public ReturnResult getFriend(Long userId, Long otherUserId, Date time, PageInfo pageInfo) {
        PageHelper.startPage(pageInfo.getPageNum(),pageInfo.getPageSize());
        List<Friend> friends = friendMapper.getFriend(userId,otherUserId,time);
        PageInfo<Friend> resultInfo=new PageInfo<Friend>(friends);
        return ReturnResult.ok(resultInfo);
    }
    
    public ReturnResult getFriendList(QueryData<FriendExample> queryData) {
        PageInfo pageInfo = queryData.getPageInfo();
        PageHelper.startPage(pageInfo.getPageNum(),pageInfo.getPageSize());
        FriendExample param = queryData.getParam();
        List<Friend> friends = friendMapper.selectListByExample(param);
        PageInfo<Friend> resultInfo=new PageInfo<Friend>(friends);
        return ReturnResult.ok(resultInfo);
    }


}
